package com.crm.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crm.common.result.PageResult;
import com.crm.common.utils.RandomStringGenerator;
import com.crm.domain.Course;
import com.crm.dto.CourseDto;
import com.crm.mapper.CourseMapper;
import com.crm.service.CourseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {
    @Autowired
    private CourseMapper courseMapper;
    @Override
    public void saveCourse(Course course) {
        log.info("保存课程信息：{}", course);
        String code = RandomStringGenerator.generateLowercase(8);
        course.setCreateTime(LocalDateTime.now());
        course.setUpdateTime(LocalDateTime.now());
        course.setCode(code);
        save(course);
    }

    @Override
    public Course getById(Long id) {
        log.info("课程查询：{}",id);
        Course course = getById(id);
        return course;
    }

    @Override
    public void updateCourse(Course course) {
        log.info("课程修改：{}",course);
        updateById(course);
    }

    @Override
    public void removeByIds(List<Long> ids) {
        log.info("课程删除：{}",ids);
        removeBatchByIds(ids);

    }

    @Override
    public PageResult list(CourseDto courseDto) {
        log.info("课程列表：{}",courseDto);

        Page<Course> page = new Page<>(courseDto.getPageNum(), courseDto.getPageSize());
        LambdaQueryWrapper<Course> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(courseDto.getCode()  != null,Course::getCode, courseDto.getCode())
                .like( courseDto.getName()  != null,Course::getName, courseDto.getName())
                .eq(courseDto.getSubject()  != null,  Course::getSubject, courseDto.getSubject())
                .eq(courseDto.getApplicablePerson() != null,Course::getApplicablePerson, courseDto.getApplicablePerson());
        if (courseDto.getParams().get("beginCreateTime")!= null&&courseDto.getParams().get("beginCreateTime") != "" &&courseDto.getParams().get("endCreateTime") != null && courseDto.getParams().get("endCreateTime") != ""){
            queryWrapper.between(Course::getCreateTime, courseDto.getParams().get("beginCreateTime"), courseDto.getParams().get("endCreateTime"))
                    .orderByDesc(Course::getCreateTime);
        }
        page(page, queryWrapper);
        return new PageResult(page.getTotal(), page.getRecords());

    }

    @Override
    public List<Course> listSelect() {
        log.info("课程列表查询");
        return super.list();
    }
}
